﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FlyHorse.LIMS.Model;
using FlyHorse.LIMS.WinApp.Utils;
using FlyHorse.LIMS.WinApp.XtraReportTemplate;
using DevExpress.XtraReports.UI;
using DevExpress.LookAndFeel;
using FlyHorse.LIMS.WinApp.Model;
using DevExpress.XtraPrinting;
using System.Drawing.Printing;

namespace FlyHorse.LIMS.WinApp.DataManageForms.ReportMixForms
{
    public partial class ReportMixMainForm : DevExpress.XtraEditors.XtraForm
    {
        BLL.GoodBll goodsBll = new BLL.GoodBll();
        BLL.ReportMixBll reportMixBll = new BLL.ReportMixBll();
        BLL.ToolBll toolBll = new BLL.ToolBll();
        IQueryable<ReportMix> _models;
        Action<ReportMix> _FillData;
        public ReportMixMainForm()
        {
            InitializeComponent();
            barLargeButtonItem_FillData.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
        }

        public ReportMixMainForm(Action<ReportMix> FillData)
        {
            InitializeComponent();
            ButtonItem_Add.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            ButtonItem_Edit.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            ButtonItem_Delete.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            ButtonItem_Print.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            ButtonItem_PrintOne.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;


            barLargeButtonItem_FillData.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
           
            _FillData = FillData;
        }

        private void ReportMixMainForm_Load(object sender, EventArgs e)
        {
            CheckAuthority();
            this.gridView2.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
            this.gridView2.OptionsBehavior.Editable = false;
            this.gridView2.OptionsSelection.EnableAppearanceFocusedCell = false;
            this.gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
            this.gridView1.OptionsBehavior.Editable = false;
            this.gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;

            //初始化下拉框
            //搜索条件的goods 下拉框
            searchLookUpEdit_Goods.Properties.DataSource = toolBll.GetSemiGoodList();
            lookUpEdit_mixPlace.Properties.DataSource = toolBll.GetMixSamplingPlaceList();

            //grid里的goods 下拉框
            repositoryItemLookUpEdit1.DataSource = goodsBll.LoadEntitiesAsNoTracking(m => true).ToList();
            //grid 取样位置
            repositoryItemLookUpEdit2.DataSource = toolBll.GetMixSamplingPlaceList();
            //grid 录入人
            repositoryItemLookUpEdit5.DataSource = toolBll.GetAllLoginUersList();
            repositoryItemLookUpEdit7.DataSource = toolBll.GetTestItemList();

            //grid载入数据
            var models = reportMixBll.LoadEntitiesAsNoTracking(m => true);
            _models = models;
            InitGrid(_models);
        }

        private void InitGrid(IQueryable<ReportMix> models)
        {

            models = models.OrderByDescending(m => m.AddDateTime).ThenByDescending(m=>m.ReportMixID);
            int pageIndex = Convert.ToInt32(this.barStaticItem_pageIndex.Caption);
            int pageSize = 0;
            try
            {
                pageSize = Convert.ToInt32(this.barEditItem_pageSize.EditValue);
            }
            catch (Exception)
            {
                XtraMessageBox.Show("页面大小值不符合规范，只能是数字！");
                return;
            }
            if (pageSize == 0)
            {
                barEditItem_pageSize.EditValue = 30;
                pageSize = 30;
            }
            splashScreenManager1.ShowWaitForm();

            PagedList<ReportMix> pagedList = new PagedList<ReportMix>(models, pageIndex, pageSize);
            this.barStaticItem_pageIndex.Caption = pagedList.PageIndex.ToString();
            this.barStaticItem_totalPage.Caption = pagedList.TotalPages.ToString();
            this.barEditItem_pageSize.Caption = pagedList.PageSize.ToString();

            this.gridControl1.DataSource = TransformReport.TransformMixReport(pagedList);
            //排序
            gridView2.BeginDataUpdate();
            try
            {
                gridView2.ClearSorting();
                gridView2.Columns["FormOrder"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
            }
            finally
            {
                gridView2.EndDataUpdate();
            }
            splashScreenManager1.CloseWaitForm();


        }

        private void ButtonItem_Add_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ReportMixDetailForm reportMixDetailForm = new ReportMixDetailForm(InitGrid);
            reportMixDetailForm.Show();
        }

        private void ButtonItem_Edit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            EditEntity();
        }


        private void EditEntity()
        {
            string ID = Convert.ToString(this.gridView1.GetFocusedRowCellValue("ReportMixID"));
            ReportMix report = reportMixBll.LoadEntities(m => m.ReportMixID == ID).FirstOrDefault();
            if (report != null)
            {
                ReportMixDetailForm reportMixDetailForm = new ReportMixDetailForm(report, InitGrid);
                reportMixDetailForm.Show();
            }
        }

        private void ButtonItem_Delete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.gridView1.GetFocusedRowCellValue("ReportMixID") != null)
            {
                DialogResult result = XtraMessageBox.Show("\n确定删除本条数据吗?   \n\n\n    确认是否退出(O/C)", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    string id = Convert.ToString(this.gridView1.GetFocusedRowCellValue("ReportMixID"));
                    using (OJCB4Entities db = new OJCB4Entities())
                    {
                        ReportMix report = db.ReportMixes.Find(id);
                        db.ReportMixes.Remove(report);
                        bool res = db.SaveChanges() > 0;
                        if (res)
                        {
                            InitGrid(_models);
                            XtraMessageBox.Show("删除成功！");
                        }
                    }
                }
            }
        }

        private void ButtonItem_Print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //object dataSource = this.gridControl1.DataSource;
            //List<ReportMixModel> reportList = (List<ReportMixModel>)dataSource;

            //XtraReportMix report = new XtraReportMix(reportList);
            //using (ReportPrintTool printTool = new ReportPrintTool(report))
            //{
            //    // Invoke the Ribbon Print Preview form modally, 
            //    // and load the report document into it.
            //    printTool.ShowRibbonPreviewDialog();
            //    // Invoke the Ribbon Print Preview form
            //    // with the specified look and feel setting.
            //    printTool.ShowRibbonPreview(UserLookAndFeel.Default);
            //}


            PreviewPrintableComponent(gridControl1, gridControl1.LookAndFeel);
        }

        private void PreviewPrintableComponent(IPrintable component, UserLookAndFeel lookAndFeel)
        {
            // Create a link that will print a control.?
            PrintableComponentLink link = new PrintableComponentLink()
            {
                PrintingSystemBase = new PrintingSystemBase(),
                Component = component,
                Landscape = true,
                PaperKind = PaperKind.A4,
                //Margins = new Margins(20, 20, 20, 20)
            };
            // Show the report.?
            link.ShowRibbonPreview(lookAndFeel);
        }

        private void simpleButton_search_Click(object sender, EventArgs e)
        {
            var models = reportMixBll.LoadEntitiesAsNoTracking(m => true);
            if (this.searchLookUpEdit_Goods.EditValue != null)
            {
                string goodsID = Convert.ToString(this.searchLookUpEdit_Goods.EditValue);
                models = models.Where(m => m.GoodsID == goodsID);
            }
            if (this.lookUpEdit_mixPlace.EditValue != null)
            {
                string placeID = Convert.ToString(this.lookUpEdit_mixPlace.EditValue);
                models = models.Where(m => m.SamplingPlaceMixID == placeID);
            }
            if (this.dateEdit_SendDateStart.EditValue != null)
            {
                models = models.Where(m => m.TestDate >= this.dateEdit_SendDateStart.DateTime);
            }
            if (this.dateEdit_SendDateEnd.EditValue != null)
            {
                models = models.Where(m => m.TestDate <= this.dateEdit_SendDateEnd.DateTime);
            }
            if (this.textEdit_LotNO.Text != "")
            {
                models = models.Where(m => m.LotNO.Contains(this.textEdit_LotNO.Text));
            }
            if (this.textEdit_ReportNO.Text!="")
            {
                models = models.Where(m => m.ReportNO.Contains(this.textEdit_ReportNO.Text));
            }

            _models = models;
            InitGrid(_models);
        }

        private void simpleButton_clear_Click(object sender, EventArgs e)
        {
            ShowAllData();
        }

        private void ShowAllData()
        {
            searchLookUpEdit_Goods.EditValue = null;
            dateEdit_SendDateStart.EditValue = null;
            dateEdit_SendDateEnd.EditValue = null;
            lookUpEdit_mixPlace.EditValue = null;
            //textEdit_SampleNO.Text = "";
            textEdit_LotNO.Text = "";
            var models = reportMixBll.LoadEntitiesAsNoTracking(m => true);
            _models = models;
            InitGrid(_models);
        }

        private void barEditItem_pageSize_EditValueChanged(object sender, EventArgs e)
        {
            InitGrid(_models);
        }


        private void barButton_firstPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.barStaticItem_pageIndex.Caption = "1";
            InitGrid(_models);
        }

        private void barButton_previousPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int pageIndex = Convert.ToInt32(this.barStaticItem_pageIndex.Caption);
            if (pageIndex >= 1)
            {
                this.barStaticItem_pageIndex.Caption = (pageIndex - 1).ToString();
                InitGrid(_models);
            }
        }

        private void barButton_nextPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int pageIndex = Convert.ToInt32(this.barStaticItem_pageIndex.Caption);
            int totalPage = Convert.ToInt32(barStaticItem_totalPage.Caption);
            if (pageIndex < totalPage)
            {
                this.barStaticItem_pageIndex.Caption = (pageIndex + 1).ToString();
                InitGrid(_models);
            }
        }

        private void barButton_lastPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int pageIndex = Convert.ToInt32(this.barStaticItem_pageIndex.Caption);
            int totalPage = Convert.ToInt32(barStaticItem_totalPage.Caption);
            if (pageIndex < totalPage)
            {
                this.barStaticItem_pageIndex.Caption = totalPage.ToString();
                InitGrid(_models);
            }
        }


        private void CheckAuthority()
        {
            List<Resource> resList = LoginUserUtil.LoginUser.Role.Resources.ToList();
            if (resList.Where(m => m.ResourceKey == "MixReportButtonItem_Add").Count() >= 1)
            {
                ButtonItem_Add.Enabled = true;
            }
            if (resList.Where(m => m.ResourceKey == "MixReportButtonItem_Edit").Count() >= 1)
            {
                ButtonItem_Edit.Enabled = true;
            }
            if (resList.Where(m => m.ResourceKey == "MixReportButtonItem_Delete").Count() >= 1)
            {
                ButtonItem_Delete.Enabled = true;
            }
            if (resList.Where(m => m.ResourceKey == "MixReportButtonItem_PrintALl").Count() >= 1)
            {
                ButtonItem_Print.Enabled = true;
            }
            if (resList.Where(m => m.ResourceKey == "MixReportButtonItem_PrintOne").Count() >= 1)
            {
                ButtonItem_PrintOne.Enabled = true;
            }
        }

        private void ButtonItem_PrintOne_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.gridView1.GetFocusedRowCellValue("ReportMixID") != null)
            {
                string id = Convert.ToString(this.gridView1.GetFocusedRowCellValue("ReportMixID"));
                XtraReportMixOne report = new XtraReportMixOne(id);
                string placeID = Convert.ToString(this.gridView1.GetFocusedRowCellValue("SamplingPlaceMixID"));
                if (!String.IsNullOrEmpty(placeID))
                {
                    if (placeID=="16")  //外来
                    {
                        using (ReportPrintTool printTool = new ReportPrintTool(report))
                        {
                            // Invoke the Ribbon Print Preview form modally, 
                            // and load the report document into it.
                            printTool.ShowRibbonPreviewDialog();
                            // Invoke the Ribbon Print Preview form
                            // with the specified look and feel setting.
                            printTool.ShowRibbonPreview(UserLookAndFeel.Default);
                        }
                    }
                    else if (placeID == "3")   //包装复检
                    {
                        using (ReportPrintTool printTool = new ReportPrintTool(report))
                        {
                            // Invoke the Ribbon Print Preview form modally, 
                            // and load the report document into it.
                            printTool.ShowRibbonPreviewDialog();
                            // Invoke the Ribbon Print Preview form
                            // with the specified look and feel setting.
                            printTool.ShowRibbonPreview(UserLookAndFeel.Default);
                        }
                    }
                    else   //其他
                    {
                        using (ReportPrintTool printTool = new ReportPrintTool(report))
                        {
                            // Invoke the Ribbon Print Preview form modally, 
                            // and load the report document into it.
                            printTool.ShowRibbonPreviewDialog();
                            // Invoke the Ribbon Print Preview form
                            // with the specified look and feel setting.
                            printTool.ShowRibbonPreview(UserLookAndFeel.Default);
                        }
                    }
                    
                }

               
            }



        }

        private void barLargeButtonItem_FillData_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.gridView1.GetFocusedRowCellValue("ReportMixID") != null)
            {
                string id = Convert.ToString(this.gridView1.GetFocusedRowCellValue("ReportMixID"));
                ReportMix report = reportMixBll.LoadEntities(m => m.ReportMixID == id).FirstOrDefault();
                if (report != null)
                {
                    _FillData(report);
                    this.Close();
                }
            }
        }


    }
}